package top.maof.lightsearch.map;

import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexableField;

import java.util.ArrayList;
import java.util.List;

public class StringMapping implements Mapping {

    @Override
    public List<IndexableField> javaMappingIndex(Parms parms) throws Exception {
        List<IndexableField> list = new ArrayList<>();

        if (parms.isIndexed() && parms.isTokenized()) {
            //索引且分词  TextField(FieldName,FieldValue, Store.NO)
            IndexableField indexableField = parms.isStored() ? new TextField(parms.getFieldName(), (String) parms.getJavaValue(), org.apache.lucene.document.Field.Store.YES)
                    : new TextField(parms.getFieldName(), (String) parms.getJavaValue(), org.apache.lucene.document.Field.Store.NO);
            list.add(indexableField);

        } else if (parms.isIndexed() && !parms.isTokenized()) {
            //只索引但不分词 StringField(FieldName, FieldValue,Store.YES))
            IndexableField indexableField = parms.isStored() ? new StringField(parms.getFieldName(), (String) parms.getJavaValue(), org.apache.lucene.document.Field.Store.YES)
                    : new StringField(parms.getFieldName(), (String) parms.getJavaValue(), org.apache.lucene.document.Field.Store.NO);
            list.add(indexableField);

        } else if (!parms.isIndexed() && !parms.isTokenized() && parms.isStored()) {
            list.add(new StoredField(parms.getFieldName(), (String) parms.getJavaValue()));
        }

        return list;
    }

    @Override
    public Object indexMappingJava(List<IndexableField> list) throws Exception {
        if (list.isEmpty()) {
            return null;
        }

        IndexableField indexableField = list.get(0);

        return indexableField.stringValue();
    }
}
